﻿var gameDao = require("./../dao/gameDao");
var gameConfig = require("./../config/gameConfig");
var redis_laba_win_pool = require("./../../util/redis_laba_win_pool");
let log = require("./../../util/loginfo").getInstand;

arithmetic = function (_idx) {
    //相关属性
    //调试是否显示相关数据
    var debug = false;

    //算法说明：
    //可选择倍数
    var betCountObj = {};
    betCountObj[1] = 1;
    betCountObj[2] = 2;
    betCountObj[5] = 3;
    betCountObj[10] = 4;
    betCountObj[20] = 5;
    betCountObj[50] = 6;
    betCountObj[100] = 7;
    var betCount = [1, 10, 20, 50, 100];


    //pro 能整除最大值
    this.pro_max = new Array();
    //pro 个数
    this.pro_max_count = new Array();
    //外部控制倍率
    this.controlBet = 0.98;
    //超级大奖占成
    this.poolBet = 0.01;
    //最大公约数
    this._testMax = 0;

    //分数数组
    this.scoreArr = {};

    //虚拟奖池
    this.virtual_score_pool = 1000000;
    //实际奖池
    this.score_pool = [];

    //========================================
    //水位
    this.nGamblingWaterLevelGold = 0;
    //库存
    this.nGamblingBalanceGold = 0;
    //奖池
    this.nGamblingWinPool = 0;
    //大奖幸运等级
    this.nGamblingBigWinLevel = [];
    //大奖幸运概率
    this.nGamblingBigWinLuck = [];

    this.printPool = function () {
        for (var i = 0; i < betCount.length; ++i) {
            log.info("i:" + i + "-" + this.score_pool[i]);
        }
    };

    //获得实际奖池
    this.getScorePool = function (_betIdx) {
        if (this.score_pool[_betIdx]) {
            this.printPool();
            return this.score_pool[_betIdx];
        } else {
            //this.printPool();
            return 0
        }

    };

    this.getScorePoolList = function () {
        return this.score_pool;
    };

    this.getScorePoolListLength = function () {
        return betCount.length;
    };

    this.getScoreId = function () {
        return betCount;
    };


    this.getGamblingBalanceGold = function () {
        //获取库存 奖池   数据库同步使用
        var dict = {
            nGamblingBalanceGold: this.nGamblingBalanceGold,
            nGamblingWinPool: this.nGamblingWinPool
        };

        return dict

    };
    this.addGamblingBalanceGold = function (Gold, Pool) {
        //添加库存 奖池   数据库同步使用
        this.nGamblingBalanceGold += parseInt(Gold);
        this.nGamblingWinPool += parseInt(Pool);
        log.info("添加库存:" + Gold);
        log.info("添加奖池:" + Pool);
        log.info(this.nGamblingBalanceGold);
        log.info(this.nGamblingWinPool);
        //redis存储奖池
        redis_laba_win_pool.redis_win_pool_incrby(parseInt(Pool))
    };
    this.subGamblingBalanceGold = function (Gold, Pool) {
        //减少库存   奖池 数据库同步使用
        //this.nGamblingBalanceGold-= parseInt(Gold);
        this.nGamblingWinPool -= parseInt(Pool);
        log.info("减少库存:" + Gold);
        log.info("减少奖池:" + Pool);
        log.info(this.nGamblingBalanceGold);
        log.info(this.nGamblingWinPool);
        //redis奖池
        redis_laba_win_pool.redis_win_pool_decrby(parseInt(Pool))
    };
    this.getGamblingBalanceLevelBigWin = function () {
        //获取库存  水位 奖池 幸运值   判断中奖使用
        var value = {
            nGamblingWaterLevelGold: this.nGamblingWaterLevelGold,
            nGamblingBalanceGold: this.nGamblingBalanceGold,
            nGamblingWinPool: this.nGamblingWinPool,
            nGamblingBigWinLevel: this.nGamblingBigWinLevel,
            nGamblingBigWinLuck: this.nGamblingBigWinLuck
        };
        return value;
    };

    //添加实际奖池
    this.addScorePool = function (_betIdx, _socre) {
        if (this.score_pool[_betIdx]) {
            this.score_pool[_betIdx] += parseInt(_socre);
        } else {
            this.score_pool[_betIdx] = 0;
            this.score_pool[_betIdx] += parseInt(_socre);
        }

        this.printPool();
    };

    //减少奖池
    this.subScorePool = function (_betIdx) {
        if (this.score_pool[_betIdx]) {
            this.score_pool[_betIdx] -= this.subValue;
        } else {
            this.score_pool[_betIdx] = 0;
        }
        this.printPool();
    };

    //获得奖池
    this.getVirtualScorePool = function () {
        //var result = {virtual_score_pool:this.virtual_score_pool,score_pool}
        return this.virtual_score_pool;
    };

    //添加奖池
    this.addVirtualScorePool = function (score_bet) {
        this.virtual_score_pool += parseInt(score_bet);
    };

    //减少虚拟奖池
    this.subVirtualScorePool = function (score_bet, flag) {
        this.subValue = Math.floor((this.virtual_score_pool / 100 * score_bet * 0.9));
        //log.info(score_bet)
        //log.info(this.virtual_score_pool)
        //log.info(this.subValue)
        if (flag) {
            this.virtual_score_pool -= this.subValue;
        } else {
            if (this.virtual_score_pool - this.subValue > 900000 || this.virtual_score_pool > 2000000) {
                this.virtual_score_pool -= this.subValue;
            }
        }

    };

    this.init = function () {
        ////debug = true;

        //初始化水位和库存
        this.initGamblingGame();


    };

    this.CheckBet = function (_betIdx) {
        return betCount[_betIdx];
    };

    this.Check_bet_dict = function (bet_dict) {
        //检查下注字典
        if ([0, 1, 2, 3, 4, 5, 6, 7].indexOf(bet_dict.bet_type) == -1) {
            log.info("缺少字段bet_type");
            return false;
        }
        if (bet_dict.bet_res == undefined) {
            log.info("缺少字段bet_res");
            return false;
        }
        if (bet_dict.bet_gold == undefined || bet_dict.bet_gold == null || bet_dict.bet_gold == 0) {
            log.info("缺少字段bet_gold");
            return false;
        }
        return true
    };

    //=================================================================================================
    this.initGamblingGame = function () {
        var self = this;
        gameDao.getGamblingGame(function (Result) {

            self.nGamblingWaterLevelGold = Result[0].nGamblingWaterLevelGold;  //水位
            self.nGamblingBalanceGold = Result[0].nGamblingBalanceGold;      //库存
            self.nGamblingWinPool = Result[0].nGamblingWinPool;      //奖池

            self.nGamblingBigWinLevel = Result[0].nGamblingBigWinLevel.split(',').map(Number);  //大奖幸运等级
            self.nGamblingBigWinLuck = Result[0].nGamblingBigWinLuck.split(',').map(Number);    //大奖幸运概率

            //redis存储奖池
            redis_laba_win_pool.redis_win_pool_incrby(self.nGamblingWinPool);


            log.info("读取采池数据完毕!");
            log.info("水位:" + self.nGamblingWaterLevelGold);
            log.info("库存:" + self.nGamblingBalanceGold);
            log.info("奖池:" + self.nGamblingWinPool);
            log.info("大奖幸运等级:" + self.nGamblingBigWinLevel);
            log.info("大奖幸运概率:" + self.nGamblingBigWinLuck);
        })


    };
    this.gameProcessor = function (betInfo_list, nGamblingWinPool, is_luck) {
        log.info("gameProcessor-------------------");
        log.info(betInfo_list);
        log.info(nGamblingWinPool);

        //# 初始化轮盘倍率
        var init_odds = gameConfig.Russian_Roulette;   //倍率
        //# 第0位 红黑 奇偶  1-18 19-36   1:1   *2
        //# 1     1-12 13-24 25-36       1:2   *3
        //# 2     6个数字组合             1:5   *6
        //# 3     4个数字组合             1:8   *9
        //# 4     3个数字组合             1:11   *12
        //# 5     2个数字组合             1:17   *18
        //# 6     1个数字                 1:35   *36
        //# 7     0,1,2,3组合              1:6   *7

        var Russian_Roulette_Odd = gameConfig.Russian_Roulette_Odd;   //对应倍率选择数组
        // 1-18, 19-36   红黑 奇偶     0  , 1,  2,3   4, 5
        // 1-12    , 13-24    , 25-36   0, 1, 2


        var init_win_result = new Array(37);  //初始化下注数组
        for (var i = 0; i < 37; i++) {
            init_win_result[i] = 0
        }


        for (var i in betInfo_list) {
            var betInfo = betInfo_list[i];    //下注详情
            var bet_res
            if (betInfo["bet_type"] == 0 || betInfo["bet_type"] == 1) {  //倍率   红黑 奇偶  1-18 19-36   1:1   *2
                bet_res = Russian_Roulette_Odd[betInfo["bet_type"]][betInfo["bet_res"]];
            } else {
                bet_res = betInfo["bet_res"];
            }
            for (var b in bet_res) {
                init_win_result[bet_res[b]] += parseInt(betInfo["bet_gold"]) * init_odds[betInfo["bet_type"]]
            }
        }

        var choice_win_result = [];
        for (var i in init_win_result) {
            if (init_win_result[i] <= nGamblingWinPool) {
                choice_win_result.push(parseInt(i))
            }
        }

        var win = RandomNumForList(choice_win_result);
        if (win == null || win == undefined) {
            log.info("开奖结果错误------------");
            return
        }

        //算账
        var user_win_list = {};
        for (var i in betInfo_list) {
            var betInfo = betInfo_list[i];    //下注详情
            log.info(betInfo);
            var bet_res
            if (betInfo["bet_type"] == 0 || betInfo["bet_type"] == 1) {  //倍率   红黑 奇偶  1-18 19-36   1:1   *2
                bet_res = Russian_Roulette_Odd[betInfo["bet_type"]][betInfo["bet_res"]];
            } else {
                bet_res = betInfo["bet_res"];
            }
            log.info("bet_res----------------------");
            log.info(bet_res);
            if (bet_res.indexOf(win) > -1) {
                if (!user_win_list[betInfo["userId"]]) {
                    user_win_list[betInfo["userId"]] = 0
                }
                user_win_list[betInfo["userId"]] += parseInt(betInfo["bet_gold"]) * init_odds[betInfo["bet_type"]]
            }
        }


        //开奖算法
        var dictAnalyseResults = {};

        dictAnalyseResults["win"] = win;
        dictAnalyseResults["win_user_list"] = user_win_list;  //# 用户获奖结果

        return dictAnalyseResults

    };


    this.init();

};


function RandomNumForList(arr) {
    //从指定数组中选取随机值
    return arr[Math.floor((Math.random() * arr.length))]

}

function RandomNumBoth(Min, Max) {
    //生成指定范围内随机整数
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    return num;
}

module.exports = arithmetic;